package com.marry.Interceptor.controller;

import com.marry.Interceptor.Entity.UserEntity;
import com.marry.Interceptor.dao.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

/**
 * 控制类
 *
 * @author ml
 * @create 2017-06-20--13:39
 */
@RestController
@RequestMapping(value = "/user")
public class LoginController {

    @Autowired
    private UserJpa userJpa;

    @RequestMapping(value = "/login")
    public String Login(UserEntity user, HttpServletRequest request){

        boolean flag=true;

        String result= "登录成功！";
        //查询用户是否存在
        UserEntity userEntity= (UserEntity) userJpa.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"),user.getName()));
                return null;
            }
        });

        if(userEntity==null){
            flag=false;
            result="用户不存在，登录失败";
        } else if(!userEntity.getPwd().equals(user.getPwd())){
            flag=false;
            result="用户密码不相符登录失败";

        }

        if(flag){
            request.getSession().setAttribute("_session_user",userEntity);

        }


        return result;

    }
}
